﻿#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com>
# - http://heavyz.blogspot.com/
# - http://buggarden.blogspot.com/
#
# Created on 2008-12-10.
# $Id: views.py 305 2008-12-19 12:51:21Z heavyzheng $
#

import logging
import datetime
import random
import urllib

from django.template import loader
from django.template import Context
from django.http import HttpRequest
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import Http404

from buggarden.apps.check.config import Config
from buggarden.apps.check.models import MODELS_REVISION
from buggarden.apps.check.models import Dummy


#---------------------------------------------------------------------------------------------------
# Common functions
#---------------------------------------------------------------------------------------------------

def _generate_random_id(prefix=""):
    timestamp = datetime.datetime.strftime(datetime.datetime.utcnow(), "%Y%m%d%H%M%S")
    suffix    = "%x" % (random.random() * 65536)
    return (prefix + timestamp + suffix)

def _get_param(query_dict, name, default=None):
    value = query_dict.get(name, "").decode("utf8").strip()
    if len(value) == 0:
        return default
    else:
        return value


def _get_common_context_dict(request):
    http_referer = request.META.get("HTTP_REFERER", "unknown_http_referer")
    remote_addr  = request.META.get("REMOTE_ADDR" , "unknown_remote_addr" )
    remote_host  = request.META.get("REMOTE_HOST" , "unknown_remote_host" )
    return { "app_name_"        : Config.APP_NAME,
             "url_prefix_"      : Config.URL_PREFIX,
             "static_"          : Config.STATIC_PREFIX,
             "models_revision_" : MODELS_REVISION,
             "http_referer_"    : http_referer,
             "remote_addr_"     : remote_addr,
             "remote_host_"     : remote_host, }


#---------------------------------------------------------------------------------------------------
# View functions
#---------------------------------------------------------------------------------------------------

def home(request):

    if request.method == "GET":
    
        # Check session.
        SESSION_KEY   = "dummy_key"
        SESSION_VALUE = "dummy_value"
        try:
            request.session[SESSION_KEY] = SESSION_VALUE
            value = request.session.get(SESSION_KEY, None)
            if value != SESSION_VALUE:
                errmsg = "Wrong value '%s' got from session for key '%s', should be '%s'." \
                       % (value, SESSION_KEY, SESSION_VALUE)
                logging.error(errmsg)
                session_test = errmsg
            else:
                session_test = "Session is OK."
        except Exception, ex:
            errmsg = "Failed to get value from session: %s" % str(ex)
            logging.error(errmsg)
            session_test = errmsg
        
        # Check database.
        try:
            db_entry_list = Dummy.get_next(1)
            if db_entry_list:
                db_entry = db_entry_list[0]
                db_entry.timestamp = datetime.datetime.utcnow()
                db_entry.ip_addr = request.META.get("REMOTE_ADDR", None)
                db_entry.accessed += 1
            else:
                db_entry = Dummy( timestamp=datetime.datetime.utcnow(),
                                  ip_addr=request.META.get("REMOTE_ADDR", None),
                                  accessed=1 )
            db_entry.put()
        except Exception, ex:
            logging.error("Failed to access model Dummy in database: %s" % str(ex))
            db_entry = None
        
        # Return the HttpResponse.
        ctxt_dict = { "message"      : "Hi, I am a Python function. Glad to serve you!",
                      "session_test" : session_test,
                      "db_entry"     : db_entry, }
        ctxt_dict.update(_get_common_context_dict(request))
        ctxt = Context(ctxt_dict)
        tmpl = loader.get_template("%s/home.html" % Config.APP_NAME)
        return HttpResponse(tmpl.render(ctxt))


def bonjour(request):
    if request.method == "GET":
        return HttpResponse("Bonjour!", mimetype="text/plain")







